import pygetwindow as gw
import tkinter as tk
from screeninfo import get_monitors

def move_and_resize_window(window, x, y, width, height):
    try:
        window.restore()
        window.activate()
        window.moveTo(x, y)
        window.resizeTo(width, height)
    except Exception as e:
        print(f"无法移动和调整窗口大小: {e}")

def minimize_other_windows(exclude_titles):
    all_windows = gw.getAllWindows()
    for window in all_windows:
        # 遍历exclude_titles列表，模糊匹配，如果窗口标题不包含在所有title，则最小化窗口
        if all(title not in window.title for title in exclude_titles):
            window.minimize()
        
def find_exact_window(windows, exact_title):
    for window in windows:
        if window.title == exact_title:
            return window
    return None

def set_window_size_based_on_screen(window, x,y,new_width,new_height):
    try:
        print(x,y,new_width,new_height)
        window.restore()
        window.activate()
        # 设置窗口大小
        window.resizeTo(new_width, new_height)
        window.moveTo(x,y)  # 居中窗口
    except Exception as e:
        print(f"无法调整窗口大小: {e}"+window.title)

def arrange_windows():
    # 查找窗口
    # window2_title = "山东通"

    windows1 = gw.getWindowsWithTitle(window1_title)
    windows2 = gw.getWindowsWithTitle(window2_title)

    if windows1 and windows2:
        # 精确匹配第二个窗口
        # window2 = find_exact_window(windows2, window2_title)
        # if not window2:
        #     print(f"无法找到标题为 '{window2_title}' 的窗口")
        #     return

        # 假设窗口大小为800x600，可以根据需要调整
        # 获取屏幕分辨率
        monitor = get_monitors()[0]
        screen_width = monitor.width
        screen_height = monitor.height - 50

        # 计算窗口大小
        new_width = int(screen_width * 0.5)
        new_height = int(screen_height * 1)

        # 将第一个窗口移动到屏幕左侧
        set_window_size_based_on_screen(windows1[0],0,0,new_width,new_height)


        # 将第二个窗口移动到第一个窗口的右侧
        set_window_size_based_on_screen(windows2[0], new_width,0,new_width,new_height)

        # 最小化其他窗口
        minimize_other_windows([windows1[0].title, window2_title,'控制窗口'])
    else:
        print("无法找到指定的窗口")

# 从title.txt文件读取两个窗口标题,utf-8编码
with open("title.txt", "r", encoding="utf-8") as file:
    window1_title = file.readline().strip()
    window2_title = file.readline().strip()

# 清空titles.txt文件
with open("titles.txt", "w", encoding="utf-8") as file:
    file.write("")
# 列出所有窗口标题
windows = gw.getAllTitles()
for i, title in enumerate(windows):
    if title:  # 过滤掉没有标题的窗口
        # 将窗口标题写入titles.txt文件
        with open("titles.txt", "a", encoding="utf-8") as file:
            file.write(title + "\n")

# 创建一个置顶窗口
root = tk.Tk()
root.title("控制窗口")
root.geometry("100x50+0+0")
root.attributes("-topmost", True)  # 设置窗口置顶
root.overrideredirect(True)  # 去掉标题栏
# 更新窗口以确保任务栏图标显示
# root.update_idletasks()

# 创建一个按钮
button = tk.Button(root, text="视频调度", command=arrange_windows)
button.pack(expand=True)
button.pack(fill=tk.BOTH, expand=True)

# 运行主循环
root.mainloop()
